<?php

namespace app\api\http\middleware;

use app\common\service\JsonService;
use app\Request;
use think\App;
use think\exception\HttpException;

class ApiValidateMiddleware
{
    public function handle(Request $request, \Closure $next)
    {

        if (strtoupper($request->controller() ) === 'PAY' && (in_array($request->action(),['notifyMnp', 'notifyOa', 'aliNotify']))){
            return $next($request);
        }
        $timestamp = $request->header('timestamp');
        $headerSign = $request->header('sign');
        $nonce = $request->header('nonce');
        if (!$headerSign || !$nonce || !$timestamp || abs( round($timestamp/1000) - time()) > 60) {
           return JsonService::fail('无效访问', [], 0, 1);
        }


        $params = $request->param();
        ksort($params);

        $paramsArr = [];
        foreach ($params as $key=>$value) {
            $value = str_replace('+','%20',urlencode($value)) ;

            $paramsArr[]="{$key}={$value}";
        }

        $sign = hash_hmac("sha256", implode('&',$paramsArr) . '&nonce=' . $nonce . '&timestamp=' . $timestamp, "1234567890");
        if ($headerSign !== $sign) {
            return JsonService::fail('无效访问', ['sign' => implode('&',$paramsArr),], 0, 1);
        }
        return $next($request);
    }
}